<?php

declare (strict_types = 1);

namespace auth;

use think\Model;

class AccessToken extends Model
{
    protected $table = 'access_token';

    /**
     * 查找匹配的 token 实例
     *
     * @param  string|null  $token
     * @return array|\auth\AccessToken|mixed|\think\Model|null
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function findToken(?string $token)
    {
        return is_null($token) ? null : static::where('token', hash('sha256', $token))->find();
    }

    /**
     * 销毁指定的 token
     *
     * @param  string  $token
     * @return bool
     */
    public static function destroyToken(string $token): bool
    {
        return (bool) static::update(['token' => null], ['token' => hash('sha256', $token)]);
    }

    /**
     * 销毁某个用户的所有 token
     *
     * @param  contract\Authenticatable  $user
     * @return bool
     */
    public static function destroyTokensOfUser(\auth\contract\Authenticatable $user): bool
    {
        return (bool) static::update(
            ['token' => null],
            ['tokenable_id' => $user->getAuthIdentifier(), 'tokenable_type' => get_class($user)]
        );
    }
}
